package com.hoshiicloud.mallshop.controller.aftersale;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hoshiicloud.common.constant.refund.RefundOrderStatusEnum;
import com.hoshiicloud.common.constant.refund.RefundServiceTypeEnum;
import com.hoshiicloud.common.constant.refund.RefundTypeEnum;
import com.hoshiicloud.common.rpc.Response;
import com.hoshiicloud.common.utils.BeanUtils;
import com.hoshiicloud.common.utils.token.UserInfoUtil;
import com.hoshiicloud.mallshop.feign.ShopSaleOrderFeignService;
import com.hoshiicloud.mallshop.feign.ShopUserFeignService;
import com.hoshiicloud.mallshop.param.UpdateRefundInfoParam;
import com.hoshiicloud.mallshop.service.aftersale.RefundManageService;
import com.hoshiicloud.saleorder.entity.Consultations;
import com.hoshiicloud.saleorder.entity.OrderMain;
import com.hoshiicloud.saleorder.entity.RefundOrder;
import com.hoshiicloud.saleorder.param.refund.RefundOrderPageParam;
import com.hoshiicloud.saleorder.vo.refund.RefundDetailVo;
import com.hoshiicloud.saleorder.vo.refund.RefundOrderVo;
import com.hoshiicloud.user.entity.company.Member;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.*;

/**
 * qry on 2019/8/12
 */
@Slf4j
@RestController
@RequestMapping("/after-sale/refund")
@Api(value = "售后管理-退款管理",tags = {"售后管理-退款管理"})
public class RefundManageController {
    private final ShopSaleOrderFeignService shopSaleOrderFeignService;
    private final ShopUserFeignService shopUserFeignService;
    private final RefundManageService refundManageService;
    public RefundManageController(ShopSaleOrderFeignService shopSaleOrderFeignService,
                                  ShopUserFeignService shopUserFeignService,
                                  RefundManageService refundManageService) {
        this.shopSaleOrderFeignService = shopSaleOrderFeignService;
        this.shopUserFeignService = shopUserFeignService;
        this.refundManageService = refundManageService;
    }

    @ApiOperation(value = "退款单分页列表")
    @PostMapping("/getPage")
    public Response<Page<RefundOrderVo>> queryMessage(@RequestBody RefundOrderPageParam param, HttpServletRequest rq) {
        param.setStoreId(UserInfoUtil.getUserInfo(rq).getStoreId());
        Response<Page<RefundOrderVo>> rs = shopSaleOrderFeignService.getRefundOrderPage(param);
        if(rs.getData().getRecords().size() == 0){
            return rs;
        }

        Set<Long> orderMainIdsss = new HashSet<>();
        Set<Long> userIdsss = new HashSet<>();
        rs.getData().getRecords().forEach(s->{
            userIdsss.add(s.getUserId());
            orderMainIdsss.add(s.getMainId());
        });

        Response<List<Member>> rsMember = shopUserFeignService.getMembersByIds(new ArrayList<>(userIdsss));
        Map<String, String> map = new HashMap<>();
        for (Member m : rsMember.getData()) {
            map.put(m.getId().toString(), m.getNickName() + "," + m.getPhone());
        }
        Response<List<OrderMain>> listOrderMainRs = shopSaleOrderFeignService.getOrderMainByIds(new ArrayList<>(orderMainIdsss));
        Map<String, String> map2 = new HashMap<>();
        for (OrderMain orderMain : listOrderMainRs.getData()) {
            map2.put(orderMain.getId().toString(), orderMain.getShippingId().toString());
        }

        for (RefundOrderVo v : rs.getData().getRecords()) {
            String[] xx = map.get(v.getUserId().toString()).split(",");
            v.setBuyerNickname(xx[0]);
            v.setBuyerPhone(xx[1]);
            this.setSpecName(v);
            v.setProductSpec(null);
            v.setShippingType(map2.get(v.getMainId().toString()));
        }
        return rs;
    }


    @ApiOperation(value = "退款单操作（同意，拒绝,收货,付款）")
    @PutMapping("/updateRefundInfo")
    public Response<Boolean> updateRefundInfo(@RequestBody @Valid UpdateRefundInfoParam param) {
       return Response.data(refundManageService.updateRefundInfo(param)) ;
    }



    @ApiOperation(value = "退款单详情")
    @GetMapping("/refundDetail2/{refundId}")
    public Response<RefundDetailVo> refundDetail2(@PathVariable("refundId") Long refundId) {
        RefundDetailVo rs = new RefundDetailVo();
        Response<RefundOrder> refundOrderRs  = shopSaleOrderFeignService.getRefundOrderById(refundId);
        if (null == refundOrderRs || refundOrderRs.getCode() != 200 || null == refundOrderRs.getData()) {
            return Response.failed("获取子订单下的退款单失败");
        }
        Response<List<Consultations>> conListRs = shopSaleOrderFeignService.listConsultationsByRefundId(refundId);
        if (null == conListRs || conListRs.getCode() != 200 || null == conListRs.getData()) {
            return Response.failed("获取子订单下的协商历史失败");
        }
        RefundOrderVo rovo ;
        try{
            rovo = BeanUtils.covertType(refundOrderRs.getData(), RefundOrderVo.class);
        }catch (Exception e){
            return Response.failed("新增订单信息异常");
        }

        Response<OrderMain> orderMainRs  = shopSaleOrderFeignService.getOrderMainById(rovo.getMainId());
        if (null == orderMainRs || orderMainRs.getCode() != 200 || null == orderMainRs.getData()) {
            return Response.failed("获取退款单的主订单信息失败");
        }

        rovo.setServiceTypeCn(RefundServiceTypeEnum.getRefundServiceType(rovo.getServiceType()));
        rovo.setRefundTypeCn(RefundTypeEnum.getRefundTypeType(rovo.getRefundType()));
        rovo.setStatusCn(RefundOrderStatusEnum.getStatusCn(rovo.getStatus()));
        this.setSpecName(rovo);

        Response<Member> rsMember = shopUserFeignService.getMembersById(rovo.getUserId());
        rovo.setBuyerNickname(rsMember.getData().getNickName());
        rovo.setBuyerPhone(rsMember.getData().getPhone());
        rovo.setProductSpec(null);
        rovo.setShippingType(orderMainRs.getData().getShippingId().toString());
        rs.setListHistory(conListRs.getData());
        rs.setRefundOrder(rovo);
        return Response.data(rs);
    }

    private void setSpecName(RefundOrderVo rovo) {
        List<String> specList = new ArrayList<>();
        Map<String, Map<String, String>> s = JSONObject.parseObject(rovo.getProductSpec(), Map.class);
        s.forEach((k, value) -> specList.add(s.get(k).get("spec_itemname")));
        rovo.setProductSpecCn(StringUtils.join(specList, "/"));
    }

}
